import { upload } from '@/api/doc'
import { FileData, UploadParams, UploadResp } from '@/plugins/oss/src/Oss'
import { Vue, Component, Prop, Emit, Ref } from 'vue-property-decorator'
import { throttle } from 'lodash'
import { resolvePath } from '@/utils/path'

@Component
export default class FileUploadMixins extends Vue {
  uploadFiles (files: FileList | File[], parent: any, load?: () => void) {
    const _throttleLoadFn = throttle(() => {
      if (load) load()
    }, 2 * 1000, { leading: false })

    for (let i = 0; i < files?.length; i++) {
      const item = files[i]
      const params: UploadParams = {
        name: item.name,
        file: item,
        path: parent?.path,
        actualPath: resolvePath(parent?.path || '', ((item as any).webkitRelativePath || item.name), '..'),
        parentId: parent?.id,
        beforeUpload: (params: UploadParams, queue: FileData[]) => {
          const name = (params.file as any).webkitRelativePath || params.name
          const has = queue.some(v => {
            const vname = (v.params.file as any).webkitRelativePath || v.params.name
            return name === vname && params.parentId === v.params?.parentId && ['uploading', 'waiting', 'cancel'].includes(v.status)
          })
          if (has) {
            const msg = '任务已在列表中'
            this.$message.warning(msg)
            return Promise.reject(new Error(msg))
          }
          return Promise.resolve()
        },
        afterUpload: (params: UploadParams, resp: UploadResp, queue: FileData[]) => {
          const name = (params.file as any).webkitRelativePath || params.name
          const req = {
            parentId: params.parentId,
            name: name,
            size: params.file?.size,
            url: resp.url
          }
          return upload(req).then(data => {
            const normal = this.$route?.query?.id === String(params.parentId) && name.indexOf('/') === -1
            const root = !this.$route?.query?.id && params.path.indexOf('/') < 0 && name.indexOf('/') === -1
            if (load && (normal || root)) {
              _throttleLoadFn()
            }
            return data
          })
        }
      }
      this.$oss.upload(params)
    }
  }
}
